<template>
  <div class="pay-way w">
    <h2 class="pay-way-title">{{ $t('选择以下支付方式') }}</h2>
    <div class="pay-way-items">
      <div :class="{ 'pay-way-item': true, 'pay-way-item-active': payIndex === i }" v-for="(item, i) in payList"
        :key="item.id" @click="itemClick(item, i)">
        <component :is="item.icon" theme="outline" size="22" :fill="item.color" strokeLinejoin="bevel"
          strokeLinecap="square" />
        <span class="pay-way-item-name">{{ $t(item.name) }}
          <span v-if="item.icon === 'WalletOne'">{{ `(¥${myBalance})` }}</span>
        </span>
      </div>
    </div>
    <div class="pay-btn-wrap">
      <Button type="error" class="pay-btn" @click="goPay">{{ $t('确认支付') }}</Button>
    </div>

    <Modal v-model="usdtModal" @on-ok="usdtOk" @on-cancel="usdtCancel" width="940">
      <div class="usdt-wrap">
        <div class="usdt-wrap-left">
          <h1 class="usdt-name">{{ getCurItem.name }}</h1>
          <img :src="usdtConfig.pic" class="usdt-cover" />
          <div class="usdt-wallet" @click="$utils.clipboard(usdtConfig.wallet)">
            {{ usdtConfig.wallet }}
            <Icon type="md-copy" />
          </div>
        </div>
        <Upload type="drag" name="file" :data="$http.returnCommonParams('api/Common/uploadPic', 'usdt')"
          :action="uploadAction" :on-success="onUploadSuccess">
          <div class="upLoad-wrap">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>{{ $t('点击或拖拽上传截图') }}</p>
          </div>
        </Upload>
        <!-- <img  class="usdt-preview" v-else :src="usdt_full_path" /> -->
      </div>
    </Modal>


    <Modal v-model="payModal" width="940">
      <div class="pay-box">
        <div class="pay-demo">
          <img src="static/img/pay/pay-demo.png" />
        </div>
        <div class="pay-qr-scan">
          <img src="static/img/pay/pay-qrscan.png" />
          <div class="pay-tips">
            <router-link to="/payDone">
              <p>点击我, 完成支付</p>
            </router-link>
          </div>
        </div>
      </div>
    </Modal>

    <!--设置支付密码-->
    <PayPassword ref="PayPasswordRef" />

    <!--输入支付密码-->
    <!-- <Modal v-model="isHasPayPwd" :title="$t('请先输入支付密码')" footer-hide width="500">
      <div class="name-wrap">
        <Input class="password-input" type="password" maxlength="6" v-model="hasUserPayPwd" :placeholder="$t('请确认密码')" />
      </div>
      <div class="forget-pwd" @click="forgetHasPwd">
        <span>忘记密码？</span>
      </div>

      <div class="modal-bottom">
        <Button type="error" @click="onConfirmBalancePay">{{ $t('提交') }}</Button>
      </div>
    </Modal> -->




    <div class="pay_code">
      <Modal v-model="isShowAliPay" @on-cancel="alipayCode = ''" title="支付宝支付" width="500">
        <div v-if="alipayCode">
          <iframe :srcdoc="alipayCode" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"
            width="300" height="300" style="overflow:hidden;">
          </iframe>
        </div>
      </Modal>
      <Modal v-model="isShowWxpay" @on-cancel="isShowWxpay = false" title="微信支付" width="500">
        <div v-if="weixinCode" style="text-align: center;">
          <img :src="weixinCode">
        </div>
      </Modal>
      <Modal v-model="isShowBank" :footer-hide="true" :mask-closable="false" @on-ok="confirmPay" @on-cancel="closePay"
        title="银联支付" width="500">
        <div>
          <Form ref="bankListRef" :model="bankList" :rules="bankListRule" :label-width="100">
            <FormItem label="姓名:" prop="name">
              <Input v-model="bankList.name" placeholder="请输入开户人姓名"></Input>
            </FormItem>
            <FormItem label="身份证号:" prop="idCard">
              <Input v-model="bankList.idCard" placeholder="请输入身份证号"></Input>
            </FormItem>
            <FormItem label="银行卡号:" prop="bankCard">
              <Input v-model="bankList.bankCard" placeholder="请输入银行卡号"></Input>
            </FormItem>
            <FormItem label="手机号：" prop="phone">
              <div class="getYzm">
                <Input v-model="bankList.phone" placeholder="请输入手机号"></Input>
                <Button style="margin-left: 10px;" :disabled="countdown > 0" @click="startCountdown">
                  {{ countdown > 0 ? countdown + '秒后获取' : '获取验证码' }}
                </Button>
              </div>
            </FormItem>
            <FormItem label="验证码：" prop="pyzm">
              <Input v-model="bankList.pyzm" placeholder="请输入手机验证码"></Input>
            </FormItem>
            <FormItem label="类别：" prop="class">
              <RadioGroup v-model="bankList.class">
                <Radio label="Ⅰ类卡"></Radio>
                <Radio label="Ⅱ类卡"></Radio>
                <Radio label="Ⅲ类卡"></Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </div>
        <div class="btnStyle">
          <Button @click="closePay">取消</Button>
          <Button style="margin-left: 20px;" type="primary" @click="confirmPay">确认</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
// payType: 6, //1 支付宝，2 微信  3 余额支付  4积分支付  5银行卡支付  6USDTTRC20支付 7USDTERC20支付 8paypal
import { Alipay, Wechat, Paypal, Dollar, WalletOne, BankCard } from "@icon-park/vue"
import WUpload from "@/components/WUpload"
import { SERVERTAPI } from '@/config/index'
const path = "api/Common/uploadPic";
import { mapState, mapActions } from 'vuex'
export default {
  name: "Cashier",
  watch: {
    countdown: {
      handler(newVal) {
        this.countdown = newVal
      }
    }
  },
  data() {
    return {
      countdown: 0,
      downTimer: null,
      isShowBank: false,

      payModal: false,
      usdtModal: false,
      payIndex: 0,
      usdtConfig: {},
      uploadAction: `${SERVERTAPI}${path}`,
      usdt_full_path: '',

      isHasPayPwd: false,
      hasUserPayPwd: '',

      isShowAliPay: false,
      alipayCode: '',
      weixinCode: '',
      timer: null,
      isShowWxpay: false,
      bankList: {
        name: "",
        idCard: '',
        phone: '',
        pyzm: '',
        bankCard: '',
        class: ''
      },
      bankListRule: {
        name: [{ required: true, message: '请输入开户人姓名', trigger: 'blur' }],
        idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        pyzm: [{ required: true, message: '请输入手机验证码', trigger: 'blur' }],
        bankCard: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
        class: [{ required: true, message: '请选择卡类别', trigger: 'change' }]
      }
    }
  },
  props: {
    orderNumber: {
      type: String,
      default: ''
    },
    //场景        会员充值 ：'recharge'，商品订单支付：'goods'，商家入驻申请：'apply'
    scene: {
      type: String,
      default: "goods",
    },
  },
  components: {
    Alipay,
    Wechat,
    WUpload,
    Paypal, Dollar, WalletOne, BankCard,
    PayPassword: () => import("@/components/authentication/PayPassword")
  },
  created() {
    this.uploadParams = { name: 'usdt' }
    this.getWalletMoney()
  },
  computed: {
    ...mapState(['myBalance']),
    getCurItem() {
      return this.payList[this.payIndex]
    },

    payList() {
      return [
        {
          type: 'ALIPAY',
          name: '支付宝支付',
          icon: 'Alipay',
          color: '#1578ff',
          payType: 1
        },
        {
          type: 'WECHAT',
          name: '微信支付',
          icon: 'Wechat',
          color: '#24b440',
          payType: 2
        },
        // {
        //   type: 'BALANCE',
        //   name: '余额',
        //   icon: 'WalletOne',
        //   color: '#1578ff',
        //   payType: 3
        // },
        // {
        //   type: 'PAYPAL',
        //   name: 'Paypal',
        //   icon: 'Paypal',
        //   color: '#012269',
        //   payType: 8
        // },
        // {
        //   type: 'USDT-TRC20',
        //   name: 'USDT-TRC20',
        //   icon: 'Dollar',
        //   color: '#32a07d',
        //   payType: 6
        // },
        // {
        //   type: 'USDT-ERC20',
        //   name: 'USDT-ERC20',
        //   icon: 'Dollar',
        //   color: '#32a07d',
        //   payType: 7
        // },
        // {
        //   type: 'BANK',
        //   name: '银行卡支付',
        //   icon: 'BankCard',
        //   color: '#1578ff'
        // },
        {
          type: 'SHOW-BANK',
          name: '银联支付',
          icon: 'BankCard',
          color: '#1578ff'
        },
      ].filter(e => {
        return this.scene === 'recharge' ? e.type !== 'BALANCE' : true
      })
    },
  },
  beforeDestroy() {
    console.log("我销毁了")
    if (this.downTimer) {
      clearInterval(this.downTimer);
      this.downTimer = null;
    }
    this.clearTimerInterval()
  },
  methods: {
    ...mapActions(['getWalletMoney']),
    itemClick(item, i) {
      this.alipayCode = ''
      this.weixinCode = ''
      this.clearTimerInterval()
      this.payIndex = i
    },
    goPay() {
      const { type } = this.getCurItem
      const types = {
        'PAYPAL': () => this.payPalPay(),
        'USDT-TRC20': () => this.usdtPay(1),
        'USDT-ERC20': () => this.usdtPay(2),
        'ALIPAY': () => this.alipay(),
        'WECHAT': () => this.wechatPay(),
        'BALANCE': () => this.balancePay(),
        'SHOW-BANK': () => this.payBank()
      }
      types[type]()
    },
    startCountdown() {
      this.countdown = 60;
      this.downTimer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.downTimer);
          this.downTimer = null;
        }
      }, 1000);
    },
    payBank() {
      this.isShowBank = true
    },
    confirmPay() {
      this.$refs.bankListRef.validate(valid => {
        if (!valid) return
        console.log(123456)
      })
    },
    closePay() {
      this.isShowBank = false
    },
    async usdtPay(type) {
      const { status, data } = await this.$http.getUsdtConfig({ type })
      if (status === 200) {
        this.usdtConfig = data
        this.usdtModal = true
      }
    },
    alipay() {
      const { payType } = this.getCurItem
      this.$Loading.start();
      this.$http
        .getzhifu({
          order_number: this.orderNumber,
          zf_type: payType,
          h5: 2,
          scene: this.scene
        })
        .then((res) => {
          if (res.status == 200) {

            // return
            const div = document.createElement('div')
            /* 下面的data.content就是后台返回接收到的数据 */
            div.innerHTML = res.data.infos
            document.body.appendChild(div)
            document.forms[0].submit()
            // this.isShowAliPay = true
          } else {
            this.$Loading.error(res.mess);
          }
        }).catch(erorr => {
          console.log('支付错误', error);
        })
    },
    wechatPay() {
      const { payType } = this.getCurItem
      this.$Loading.start();
      this.$http
        .getzhifu({
          order_number: this.orderNumber,
          zf_type: payType,
          wechat_miniprogram: 2,
          scene: this.scene
        })
        .then((res) => {
          if (res.status == 200) {
            this.isShowWxpay = true
            this.weixinCode = res.data.infos
            this.timer = window.setInterval(() => {
              this.searchGetOrder()
            }, 5000);
          } else {
            this.$Loading.error(res.mess);
          }
        }).catch(erorr => {
          console.log('支付错误', error);
        })
    },

    /**
     * 订单轮询支付
     */
    searchGetOrder() {
      this.$http.searchGetOrder({
        order_number: this.orderNumber
      }).then((res) => {
        if (res.status == 200) {
          this.$router.push({ path: '/My', query: { name: 'MyOrder' } })
        } else {
          console.log(res.mess)
        }
      }).catch(erorr => {

      })
    },

    /**
     * 清除轮询
     */
    clearTimerInterval() {
      window.clearInterval(this.timer);
    },

    /**
     * 余额支付
     */
    balancePay() {
      this.$http.hasPayPwd().then((res) => {
        if (res.status == 200) {
          this.isHasPayPwd = true
        } else {
          this.$refs.PayPasswordRef.handleRender()
        }
      }).catch(erorr => {
        console.log('余额支付错误', error);
      })
    },

    /**
     * 忘记密码
     */
    forgetHasPwd() {
      this.$refs.PayPasswordRef.handleRender()
    },

    /**
     * 余额确定支付
     */
    onConfirmBalancePay() {
      const { payType } = this.getCurItem
      this.$Loading.start();
      this.$http.getzhifu({
        order_number: this.orderNumber,
        zf_type: payType,
        pay_password: this.hasUserPayPwd,
        scene: this.scene
      })
        .then((res) => {
          if (res.status == 200) {
            this.password = "";
            this.$Loading.finish();
            this.$Message.success(res.mess)
            if (this.scene == 'goods') {
              this.$router.push({
                path: '/My',
                query: {
                  tabIndex: 1,
                  subType: 6,
                }
              })
              // if(this.scene == 'apply'){}
              //
            }
          } else {
            if (res.status === 400) {

            }
            this.$Loading.error();
          }
        }).catch(erorr => {
          console.log('余额支付错误', error);
        })
    },




    usdtOk() {
      this.submitPay()
    },
    async submitPay() {
      const { payType, type } = this.getCurItem
      const data = {
        zf_type: String(payType),
        order_number: this.orderNumber,
        scene: this.scene,
      };
      if (['USDT-TRC20', 'USDT-ERC20'].includes(type)) {
        if (!this.usdt_full_path) {
          return this.$Message.error('请上传USDT支付截图')
        }
        data.usdt_img = this.usdt_full_path
      }
      const { status, mess } = await this.$http.getzhifu(data)
      if (status === 200) {
        this.$Message.success(mess)
        this.$router.replace({ path: '/My', query: { name: 'MyOrder', subType: 6 } })
      }
    },
    usdtCancel() {
      this.usdt_full_path = ''
    },
    onUploadSuccess(e) {
      const { status, data: { full_path } } = e
      if (status === 200) {
        this.usdt_full_path = full_path
      }
    }

  }
}
</script>

<style lang="scss" scoped>
@import "@/common/style/common.scss";

.pay-way {
  padding: 30px 30px 20px;
  background-color: #fff;
  margin-top: 20px;


  &-title {
    font-size: 20px;
    padding: 0 20px 20px;
    font-weight: 600;
    border-bottom: 1px solid #eee;
  }

  &-items {
    @include flex();
    padding: 20px 0;
  }

  &-item {
    @include flex(center);
    border: 1px solid #eee;
    margin-right: 30px;
    padding: 18px 0;
    width: 220px;
    margin-top: 20px;
    transition: all 0.4s;
    cursor: pointer;

    &-active {
      border: 2px solid;
      color: #e2231a;
    }

    &-name {
      margin-left: 10px;
      font-weight: 500;
    }
  }

  .pay_code {
    position: fixed;
    top: 100px;
    left: 30%;
  }
}

.usdt {
  &-wrap {
    display: flex;
    align-items: center;
    min-height: 410px;
    padding: 30px 40px;

    &-left {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      margin-right: 70px;
    }
  }

  &-preview {
    width: 200px;
    height: 300px;
  }

  &-name {
    font-size: 22px;
    margin-bottom: -60px;
    position: relative;
    z-index: 99;
  }

  &-cover {
    width: 380px;
    height: 380px;
  }

  &-wallet {
    background-color: #deeaff;
    border-radius: 2px;
    display: inline-block;
    padding: 2px 8px;
    margin-top: -60px;
  }
}

.pay-btn {
  height: 50px;
  padding: 0 50px;
  border-radius: 0;
  font-size: 16px;

  &-wrap {
    margin-top: 140px;
    @include flex($jc: flex-end);
  }
}

.upLoad-wrap {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  border: 1px dashed #eee;
  padding: 30px 80px;
}

.modal-bottom {}

.forget-pwd {
  height: 40px;
  line-height: 40px;
  color: blue;
  text-align: right;
  cursor: pointer;
}

.getYzm {
  display: flex;

}

.btnStyle {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
